package com.sparrow.manage.article;

import com.sparrow.manage.common.dao.AttachmentDao;
import com.sparrow.manage.common.entity.Attachment;
import com.sparrow.manage.common.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ArticleServiceImpl extends BaseServiceImpl<Article, String> implements ArticleService {

    @Autowired
    private ArticleDao articleDao;

    @Override
    protected JpaRepository<Article, String> getDao() {
        return articleDao;
    }

    @Override
    public Article insert(Article article) {
        Article record = articleDao.save(article);
        this.saveAttachmentForArticle(article.getHeadImage(), record);
        return record;
    }

    @Override
    public Article updateById(Article article) {
        if(StringUtils.isBlank(article.getId())){
            return null;
        }
        Article record = articleDao.save(article);
        this.saveAttachmentForArticle(article.getHeadImage(), record);
        return record;
    }

    @Autowired
    private AttachmentDao attachmentDao;

    private void saveAttachmentForArticle(Attachment attachment, Article article){
        if(attachment != null){
            attachment.setRelateId(article.getId());
            attachment.setCreateTime(article.getCreateTime());
            attachment.setCreateUser(article.getCreateUser());
            attachmentDao.deleteByRelateId(article.getId());
            attachmentDao.save(attachment);
        }
    }

    @Override
    public void updateCarousel(String id, Integer carousel) {
        articleDao.updateCarouselById(carousel, id);
    }

    @Override
    public List<Article> queryByType(Article.ArticleType type, int size) {
        List<Article> articles = articleDao.queryByType(type.getCode(), size);

        Set<String> ids = new HashSet<>();
        for(Article article : articles){
            ids.add(article.getId());
        }
        if(!ids.isEmpty()){
            List<Attachment> attachments = attachmentDao.queryByRelateIds(ids.toArray(new String[ids.size()]));
            if(!attachments.isEmpty()){
                Map<String, Attachment> map = new HashMap<>();
                for(Attachment att : attachments){
                    map.put(att.getRelateId(), att);
                }

                for(Article article : articles){
                    article.setHeadImage(map.get(article.getId()));
                }
            }

        }

        return articles;
    }

    @Override
    public List<Article> queryCarousel(int size) {
        return articleDao.queryCarousel(size);
    }

}
